<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never" style="min-height: 800px">
      <el-row>
        <div style="border-right: solid 1px var(--el-border-color)">
          <el-col :span="6">
            <el-tree style="width: 300px" :data="treeList" node-key="id" default-expand-all>
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span @click="handleNodeClick(data)">{{ node.label }}</span>
                  <span style="padding-left: 60px" v-if="data.id && data.id > 0">
                    <a @click="editNode(data)"> 修改 </a>
                  </span>
                  <span style="padding-left: 3px" v-if="data.id && data.id > 0">
                    <a @click="addNode(data)"> 新增下级 </a>
                  </span>
                  <span style="padding-left: 60px" v-else>
                    <a @click="addNode(data)"> 新增顶级 </a>
                  </span>
                  <span style="padding-left: 3px" v-if="data.id && data.id > 0">
                    <a @click="delNode(data)"> 删除 </a>
                  </span>

                </span>
              </template>
            </el-tree>
          </el-col>
        </div>
        <el-col :span="18" style="padding-left: 10px">
          <el-form v-show="showSearch" :inline="true" id="searchFormId" @submit.prevent>
            <el-form-item label="名称" prop="name">
              <el-input placeholder="请输入名称" v-model="searchParams.name" clearable style="width: 240px"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
              <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-upload
                :on-success="handleSuccess"
                :on-error="uploadError"
                :show-file-list="false"
                :action="props.action"
                :data="uploadData"
                :headers="headers"
                :accept="fileType.join(',')"
                multiple
              >
                <el-button type="primary" plain icon="upload">上传</el-button>
              </el-upload>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain @click="handleSubmit()">使用选中图片</el-button>
            </el-col>
            <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
          </el-row>
          <el-divider />
          <div class="images_list">
            <ul>
              <li
                v-for="(item, index) in tableList"
                :key="index"
                class="block"
                :class="{
                  active: selectList.findIndex((r: any) => r.id == item.id) > -1
                }"
                @click="selectFile(item)"
                style="position: relative; cursor: pointer"
              >
                <el-image style="width: 100px; height: 100px" :src="item.url" fit="fill" lazy />
                <el-tooltip placement="top" :content="item.name">
                  <span class="demonstration">{{ item.name }}</span>
                </el-tooltip>

                <span class="img-del-x">
                  <el-icon @click="handleDel($event, item)"><CloseBold /></el-icon>
                </span>
              </li>
            </ul>
          </div>
          <br />
          <el-pagination
            background
            v-model:current-page="searchParams.pageNo"
            v-model:page-size="searchParams.pageSize"
            v-show="total > 0"
            :page-sizes="[10, 20, 50, 100, 200]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleListPage"
            @current-change="handleListPage"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ColeAttachmentDialog">
import { onMounted, ref } from "vue";
import { addCategory, deleteCateId, listTreePage, updateCategory } from "@/api/system/attachment/category";
import { koiMsgBox, koiMsgSuccess, koiNoticeError, koiNoticeSuccess, koiNoticeWarning } from "@/utils/koi.ts";
import { remove, listPage } from "@/api/system/attachment/attachment";
import { ElMessageBox } from "element-plus";
import { getToken } from "@/utils/storage";

interface IAttachmentProps {
  canUploadedNum?: number; //还可以选中多少个
  type?: string; //文件类型 image图片 video视频
  canSelectedLimit?: number; //限制可选
  alreadySelected?: number; //已经选中多少个
  fileSize?: number;
  action?: string;
  folderName?: string; // 后端文件夹名称
  fileType?: any; //图片类型限制 ==> 非必传（默认为 ["image/webp","image/jpg", "image/jpeg", "image/png", "image/gif"]）
}

//文件上传头
const headers = {
  Authorization: "Bearer " + getToken()
};
//文件上传附加参数
const uploadData = () => {
  return {
    // file:"",
    fileType: "2",
    folderName: props.folderName,
    // fileSize: "",
    category_id: searchParams.value.category_id,
    add_attach: "1"
  };
};
const props = withDefaults(defineProps<IAttachmentProps>(), {
  fileType: () => ["image/webp", "image/jpg", "image/jpeg", "image/png", "image/gif"],
  fileSize: 20, //mb
  folderName: "pictures", //mb
  type: "image",
  action: import.meta.env.VITE_WEB_BASE_API + "/admin/system/upload/uploadFile"
});
// 当前组件获取父组件传递的事件方法
const emits = defineEmits(["handleSubmit"]);
// 弹框的确定事件
const handleSubmit = () => {
  if (selectList.value.length <= 0) {
    koiNoticeWarning("请先选中图片");
    return;
  }
  emits("handleSubmit", selectList.value);
};

// 数据表格加载页面动画
const loading = ref(false);
const total = ref(0);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
const tableList = ref<any>([]);
const treeList = ref<any>([]);
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 15, // 每页显示多少条
  name: "",
  category_id: ""
});
const handleNodeClick = (node: any) => {
  searchParams.value.category_id = node.id;
  handleSearch();
};
// 校验上传文件格式

const handleSuccess = (response: any, uploadFile: any, fileList: any) => {
  if (!response) return;
  uploadFile.url = response;
  if (fileList.every((it: any) => it.status == "success")) {
    koiNoticeSuccess("上传完成");
    handleSearch();
  }
};
const uploadError = () => {
  koiNoticeError("图片上传失败，请您重新上传");
};
const editNode = (node: any) => {
  ElMessageBox.prompt(node.label, "请填写修改后的内容", {
    confirmButtonText: "修改",
    cancelButtonText: "关闭"
  })
    .then(({ value }) => {
      updateCategory({ name: value, id: node.id }).then(() => {
        koiMsgSuccess("修改成功");
        handleTreeList();
      });
    })
    .catch(() => {
      // koiMsgSuccess("修改失败");
    });
};
const addNode = (node: any) => {
  let msg = "新增顶级分类";
  let pid = 0;
  if (node.id) {
    msg = "新增下级分类";
    pid = node.id;
  }
  ElMessageBox.prompt(msg, "新增分类", {
    confirmButtonText: "修改",
    cancelButtonText: "关闭"
  })
    .then(({ value }) => {
      addCategory({ name: value, pid: pid }).then(() => {
        koiMsgSuccess("新增成功");
        handleTreeList();
      });
    })
    .catch(() => {
      // koiMsgSuccess("修改失败");
    });
};
const delNode = (node: any) => {
  koiMsgBox("您确认需要进行删除[" + node.label + "]么？")
    .then(async () => {
      deleteCateId({ id: node.id }).then(() => {
        handleTreeList();
        koiNoticeSuccess("删除成功");
      });
    })
    .catch();
};

const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1, // 第几页
    pageSize: 15, // 每页显示多少条
    name: "",
    category_id: ""
  };
};
onMounted(() => {
  handleTreeList();
  handleListPage();
});
/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.pageNo = 1;
  handleListPage();
};
const handleDel = (event: Event, row: any) => {
  event.stopPropagation();
  koiMsgBox("您确认需要进行删除[" + row.name + "]么？")
    .then(async () => {
      try {
        await remove({ id: row.id });
        handleSearch();
        koiNoticeSuccess("删除成功");
      } catch (error) {
        console.log(error);
        handleSearch();
      }
    })
    .catch();
};

const selectList = ref<any>([]);
const selectFile = (row: any) => {
  const idx = selectList.value.findIndex((r: any) => r.id == row.id);
  if (idx > -1) {
    selectList.value.splice(idx, 1);
  } else {
    if ((props.canUploadedNum as any) <= selectList.value.length) {
      koiNoticeWarning(`已经超过本次可上传数量:${props.canUploadedNum};限制${props.alreadySelected}/${props.canSelectedLimit}`);
      return;
    }
    selectList.value.push(row);
  }
};
/** 搜索 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage({ ...searchParams.value, type: props.type });
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleSearch();
};

const handleTreeList = async () => {
  try {
    treeList.value = []; // 重置表格数据
    loading.value = true;
    const res: any = await listTreePage({});
    res.data.unshift({
      id: "",
      label: "全部分类",
      children: []
    });
    treeList.value = res.data;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};
</script>

<style lang="scss" scoped>
.images_list .block {
  padding: 10px;
  text-align: center;
  display: inline-block;
  box-sizing: border-box;
  vertical-align: top;
  margin: 3px;
  box-shadow: 1px 1px 17px 2px #e0e0e0;
  border-radius: 5px;
  width: 180px;
  height: 150px;
}

.active {
  border-radius: 5px;
  border: 2px solid #3b91ff;
  background-color: #f1f5fa;
}

.images_list .block:last-child {
  border-right: none;
}

.images_list .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.img-del-x {
  position: absolute;
  z-index: 100;
  top: -4px;
  right: -4px;
  width: 20px;
  height: 20px;
  font-size: 16px;
  line-height: 16px;
  color: #fff;
  text-align: center;
  cursor: pointer;
  background: hsla(0, 0%, 60%, 0.6);
  border-radius: 10px;
}
</style>
